import fetch from "dva/fetch";
import { notification } from "antd";
import { routerRedux } from "dva/router";
import axios from "axios";
import store from "store";
import querystring from "querystring";
import store1 from "../index";
import config from "./config";

notification.config({
  placement: 'topLeft',
  bottom: 50,
  duration: 3,
});
const instance = axios.create({
  baseURL: "https://api.example.com",
  timeout: 20000,
  headers: {
    Authorization: "Basic c2Fhc3dlYjp3ZWI=",
    Accept: "application/json",
    "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
  }
});

let timeid;
/* instance.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded;charset=UTF-8"; */

/* 本地开发环境  */
let host = config.dailyhost;

/* 测试环境*/
if (window.location.port === "8005") {
  host = config.testhost;
}

function checkStatus(response) {
  console.log(response, "response");
  if (response.status >= 200 && response.status < 300) {
    return response;
  }
  notification.error({
    message: `请求错误 ${response.status}: ${response.url}`,
    description: response.statusText
  });
  const error1 = new Error(response.statusText);
  error1.response = response;
  throw error1;
}

function getHostByPath() {
  if (window.location.port === "8005") {
    host = config.testhost;
  } else {
    host = config.dailyhost;
  }
  return host;
}

export { getHostByPath };

/**
 * 需要登录
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */

export function request(path, options, testUrl) {
  const url = testUrl || getHostByPath() + path;
  //console.log("测试路径：",url);
  const defaultOptions = {
    credentials: "include"
  };
  const newOptions = {
    ...defaultOptions,
    ...options
  };
  if (newOptions.method === "POST" || newOptions.method === "PUT") {
    newOptions.headers = {
      ...newOptions.headers
    };
    newOptions.body = JSON.stringify({ ...newOptions.body, v: "v1.0" });
  }

  if (options && options.data) {
    delete newOptions.body;
    if (store.get("saas") === undefined) {
      const { dispatch } = store1;
      dispatch(routerRedux.push("/user/logOn"));
      notification.error({
        message: "请登录"
      });
      return;
    }
    const method = options.method.toLowerCase();
    return axios({
      url,
      method,
      headers: {
        access_token: store.get("saas")["access_token"]
      },
      params: method === "get" ? { ...options.data, api: url, v: "v1.0" } : {},
      data:
        method === "post"
          ? querystring.stringify({ ...options.data, api: url, v: "v1.0" })
          : {}
    })
      .then(response => {
        const { status, data } = response;
        if (data.retType === "1") {
          store.remove();
          //防止重复提示
          clearTimeout(timeid);
          timeid = window.setTimeout(() => {
            notification.error({
              message: data.msg
            });
          }, 500);

          const { dispatch } = store1;
          dispatch(routerRedux.push("/user/logOn"));
          return Promise.reject(data);
        }
        if (status !== 200 || data.retType !== "0") {
          notification.error({
            message: data.msg
          });
          return Promise.reject(data);
        }
        if (method === "post" && data.msg) {
          notification.success({
            message: data.msg
          });
        }
        let newData1;
        try {
          newData1 = JSON.parse(JSON.stringify(data).replace(/null/g, '""'));
        } catch (err) {
          newData1 = data;
        }

        return newData1;
      })
      .catch(err => {
        console.log(err, "err");
        if (err.toString().indexOf("Network") !== -1) {
          notification.error({
            message: "网络出错了"
          });
          // const { dispatch } = store1;
          //dispatch(routerRedux.push("/user/logOn"));
        }
        return Promise.reject(err);
      });
  } else {
    return fetch(url, { ...newOptions, api: url, v: "v1.0" })
      .then(checkStatus)
      .then(response => response.json())
      .catch(error => {
        if (error.code) {
          notification.error({
            message: error.name,
            description: error.message
          });
        }
        if ("stack" in error && "message" in error) {
          notification.error({
            message: `请求错误: ${url}`,
            description: error.message
          });
        }
        return error;
      });
  }
}

/* 不需要登录 */
export function noLoginRequest(path, options) {
  const url = getHostByPath(path) + path;
  console.log(path, "path");
  //console.log("测试路径：",url);
  const defaultOptions = {
    credentials: "include"
  };
  const newOptions = {
    ...defaultOptions,
    ...options
  };
  if (newOptions.method === "POST" || newOptions.method === "PUT") {
    newOptions.headers = {
      ...newOptions.headers
    };
    newOptions.body = JSON.stringify({ ...newOptions.body, v: "v1.0" });
    // newOptions.body = {...newOptions.body, v: "v1.0"};
  }

  const method = options.method.toLowerCase();
  return axios({
    url,
    method,
    params: method === "get" ? { ...options.data, api: url, v: "v1.0" } : {},
    data:
      method === "post"
        ? querystring.stringify({ ...options.data, api: url, v: "v1.0" })
        : {}
  })
    .then(response => {
      const { status, data } = response;
      if (data.retType === "1") {
        notification.error({
          message: data.msg
        });
        const { dispatch } = store1;
        dispatch(routerRedux.push("/user/logOn"));
        return Promise.reject(data);
      }
      if (status !== 200 || data.retType !== "0") {
        notification.error({
          message: data.msg
        });
        return Promise.reject(data);
      }
      if (method === "post" && data.msg) {
        notification.success({
          message: data.msg
        });
      }

      let newData1;
      try {
        newData1 = JSON.parse(JSON.stringify(data).replace(/null/g, '""'));
      } catch (err) {
        newData1 = data;
      }

      return newData1;
    })
    .catch(err => {
      console.log(err, "err");
      if (err.toString().indexOf("Network") !== -1) {
        notification.error({
          message: "网络出错了"
        });
        const { dispatch } = store1;
        dispatch(routerRedux.push("/user/logOn"));
      }
      return Promise.reject(err);
    });
}

/* 登录请求
注意：本应该是post请求提交的参数确要用get提交参数后期要后端整改
---------------------------------------------------*/
export function loginRequest(path, options) {
  const url = getHostByPath(path) + path;
  return instance
    .post(url, {
      ...options.data,
      api: url,
      v: "v1.0",
      grant_type: "password"
    })
    .then(response => {
      const { status, data } = response;
      if (status === 200 && data.retType === "0") {
        console.log("set");
        store.set("saas", {
          access_token: data.data.access_token,
          sessionId: encodeURIComponent(data.data.sessionId)
        });
      } else {
        notification.error({
          message: data.msg
        });
      }
      console.log(response, "instance-登录");
      return data;
    })
    .catch(err => {
      console.log(err, "err");
      if (err.toString().indexOf("Network") !== -1) {
        notification.error({
          message: "网络出错了"
        });
      }
      return { status: 600, data: { retType: "-1" } };
    });
}
